package com.yk._02多线程消费差;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class _02锁消费者生产者的写法 {
    public static void main(String[] args) {
        ResourceLock resource_lock = new ResourceLock();
        new Thread(() -> {
            for (int j = 0; j < 30; j++) {
                resource_lock.producer();
            }
        }).start();

        new Thread(() -> {
            for (int j = 0; j < 30; j++) {
                resource_lock.consumer();
            }
        }).start();
    }

}


@Data
@AllArgsConstructor
@NoArgsConstructor
class ResourceLock {
    private int num = 0;
    public final ReentrantLock lock = new ReentrantLock();
    public final Condition condition = lock.newCondition();

    @SneakyThrows
    public void producer() {

        lock.lock();
        try {
            //业务代码
            while (num != 0) {//这里不能写 if 否则会出现虚假唤醒
                condition.await();
            }
            num++;
            System.err.println(Thread.currentThread().getName() + " 生产成功 num=" + num);
            condition.signalAll();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    @SneakyThrows
    public synchronized void consumer() {
        lock.lock();

        try {
            while (num == 0) {//这里不能写 if 否则会出现虚假唤醒
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + " 消费成功 num=" + num);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
